from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django.utils import timezone
from datetime import datetime, date, timedelta
from django.db import transaction

from .models import Course, CourseReminder, Semester
from .serializers import (
    CourseSerializer,
    CourseReminderSerializer,
    SemesterSerializer,
    ImportCourseSerializer
)


class CourseViewSet(viewsets.ModelViewSet):
    """课程视图集"""
    serializer_class = CourseSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return Course.objects.filter(user=self.request.user)

    def _get_current_week(self):
        """根据当前学期起止日期计算教学周。"""
        semester = Semester.objects.filter(user=self.request.user, is_current=True).first()
        if not semester or not semester.start_date:
            return None
        today = date.today()
        if today < semester.start_date:
            return None
        if semester.end_date and today > semester.end_date:
            return None
        return ((today - semester.start_date).days // 7) + 1

    def _filter_by_week(self, queryset, week):
        if not week:
            return queryset.none()
        return queryset.filter(start_week__lte=week, end_week__gte=week)

    @action(detail=False, methods=['get'])
    def weekly(self, request):
        """获取本周课程"""
        current_week = self._get_current_week()
        courses = self._filter_by_week(self.get_queryset(), current_week)
        serializer = self.get_serializer(courses, many=True)
        return Response(serializer.data)

    @action(detail=False, methods=['get'])
    def today(self, request):
        """获取今日课程"""
        today_weekday = datetime.now().isoweekday()
        current_week = self._get_current_week()
        courses = self._filter_by_week(self.get_queryset(), current_week).filter(weekday=today_weekday)
        serializer = self.get_serializer(courses, many=True)
        return Response(serializer.data)

    @action(detail=False, methods=['post'])
    def import_from_educational(self, request):
        """从教务系统导入课程"""
        serializer = ImportCourseSerializer(data=request.data)
        if serializer.is_valid():
            # TODO: 实现教务系统对接逻辑
            # 这里需要根据具体学校的教务系统API进行对接
            return Response({
                'message': '课程导入功能正在开发中',
                'status': 'coming_soon'
            })
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    @action(detail=False, methods=['delete'])
    def clear_all(self, request):
        """清空所有课程"""
        count = self.get_queryset().count()
        self.get_queryset().delete()
        return Response({
            'message': f'已删除 {count} 门课程'
        })

    @action(detail=False, methods=['post'], url_path='bulk_create')
    def bulk_create(self, request):
        """批量创建课程"""
        if not isinstance(request.data, list) or not request.data:
            return Response(
                {'message': '请求体需为非空数组'},
                status=status.HTTP_400_BAD_REQUEST
            )

        serializer = self.get_serializer(data=request.data, many=True)
        serializer.is_valid(raise_exception=True)

        created_courses = []
        with transaction.atomic():
            for item in serializer.validated_data:
                course = Course.objects.create(user=request.user, **item)
                created_courses.append(course)

        output_serializer = self.get_serializer(created_courses, many=True)
        return Response(
            {
                'created': len(created_courses),
                'courses': output_serializer.data
            },
            status=status.HTTP_201_CREATED
        )

class CourseReminderViewSet(viewsets.ReadOnlyModelViewSet):
    """课程提醒视图集"""
    serializer_class = CourseReminderSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return CourseReminder.objects.filter(user=self.request.user)

    @action(detail=False, methods=['get'])
    def upcoming(self, request):
        """获取即将到来的提醒"""
        now = timezone.now()
        reminders = self.get_queryset().filter(
            status='pending',
            reminder_time__gte=now,
            reminder_time__lte=now + timedelta(days=1)
        )
        serializer = self.get_serializer(reminders, many=True)
        return Response(serializer.data)


class SemesterViewSet(viewsets.ModelViewSet):
    """学期视图集"""
    serializer_class = SemesterSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return Semester.objects.filter(user=self.request.user)

    @action(detail=False, methods=['get'])
    def current(self, request):
        """获取当前学期"""
        semester = self.get_queryset().filter(is_current=True).first()
        if semester:
            serializer = self.get_serializer(semester)
            return Response(serializer.data)
        return Response({'message': '未设置当前学期'}, status=status.HTTP_404_NOT_FOUND)

    @action(detail=True, methods=['post'])
    def set_current(self, request, pk=None):
        """设置为当前学期"""
        semester = self.get_object()
        Semester.objects.filter(user=request.user, is_current=True).update(is_current=False)
        semester.is_current = True
        semester.save()
        return Response({'message': '已设置为当前学期'})
